import json

from pandas import DataFrame

from common.mydb import SQL
from common.pd import get_tb_data, DF_Table
from common.config import Public_Data
from log import Log
from qttab.sqlite_db import delete_by_id_list
from repository.doc_drcs_db import insert_many_doc_drcs
from repository.doc_idrs_db import insert_many_doc_idrs
from repository.drcs_db import insert_drcs_by_dict
from repository.idrs_db import insert_idrs_by_dict

log = Log()


def get_loc_unique_list(doc_df: DataFrame, col_name):
    """获取dataframe 数据中的某列的不重复值"""
    return doc_df[col_name].unique().tolist()


# region fax 相关操作

# endregion

# region doc_f 相关操作


# endregion

# region idrs和drcs 表的相关操作


def doc_df_to_review_tb(df_doc: DataFrame, is_idrs=0):
    """根据文件信息创建DRCS和IDRS数据"""
    if not df_doc.empty:
        massage_name = "DRCS"
        channel_code_list = df_doc["channel"].unique().tolist()
        for channel in channel_code_list:
            df_chanel_doc = df_doc.loc[df_doc["channel"] == channel]  # 获取通道号中的所有文件
            doc_info: DataFrame = df_chanel_doc[["id", "title", "contract_id"]]
            doc_inf_dic = doc_info.to_dict("list")
            contract_list = doc_inf_dic["contract_id"]
            # DRCS所需要的信息：
            review_dict = {}
            # 获取标题信息
            title_list = doc_inf_dic["title"]
            title = title_list[0]
            if len(title_list) > 1:
                title = title_list[0] + "等文件"
            if is_idrs:
                massage_name = "IDRS"
                review_dict["title"] = title + "的协审"
                review_dict["comment"] = "请审查制造厂提交的文件：" + title
            else:

                review_dict["title"] = title + "审查意见"
                review_dict["overall_view"] = "审查意见详见文件意见"
            review_dict["contract_id"] = contract_list[0]
            review_dict["doc_channel"] = channel
            if is_idrs:
                data_id = insert_idrs_by_dict(review_dict)
            else:
                data_id = insert_drcs_by_dict(review_dict)

            if review_dict and data_id:
                doc_id_list: list = doc_inf_dic["id"]
                if doc_id_list:
                    data_list = []
                    for doc_id in doc_id_list:
                        insert_data = [doc_id, data_id]
                        data_list.append(insert_data)
                    if is_idrs:
                        insert_many_doc_idrs(["doc_id", "review_id"], data_list)

                    else:
                        insert_many_doc_drcs(["doc_id", "review_id"], data_list)
                else:
                    log.error(f"未获取{channel}的文件")

            else:
                log.error(f"{channel}创建新{massage_name}不成功")


# fax to idrs
def insert_fax_to_idrs(df_fax: DataFrame):
    """
    把fax：DataFrame 添加到IDRS的数据表中
    """
    if not df_fax.empty:
        row_index_list = df_fax.index.tolist()
        datas = []
        for index in row_index_list:
            file_channel = df_fax.loc[index, "channel"]
            fax_title = df_fax.loc[index, "title"].strip()

            title = f"关于函件《{fax_title}》的协审"
            project = df_fax.loc[index, "project"].strip()
            contract_id = int(df_fax.loc[index, "contract_id"])
            comment = f"请审查制造厂提交的函件《{fax_title}》"
            datas.append([project, file_channel, title, contract_id, comment])
        sql = SQL()
        idrs_col_name_list = ['project', "file_channel", 'title', 'contract_id', 'comment']
        sql.insert_many("idrs", idrs_col_name_list, datas)
        return {"rst": True, "data": None, "msg": f"添加{len(datas)}个函件的协审成功，请到IDRS页面发起流程"}
    return {"rst": False, "data": None, "msg": f"未生成要发起的函件IDRS"}


def update_drcs(change_dict: dict):
    sql = SQL()
    doc_review_col_name_list = sql.get_col_name("doc_review")
    drcs_col_name_list = sql.get_col_name("drcs")
    for drcs_doc_id in change_dict.keys():
        change_data_dict: dict = change_dict[drcs_doc_id]
        doc_review_change_dic = {}
        drcs_change_dict = {}
        for col_name in change_data_dict.keys():
            if col_name in doc_review_col_name_list:
                doc_review_change_dic[col_name] = change_data_dict[col_name]

            elif col_name in drcs_col_name_list:
                drcs_change_dict[col_name] = change_data_dict[col_name]

        if doc_review_change_dic:
            sql.update_one_by_dict("doc_review", doc_review_change_dic, drcs_doc_id)
        if drcs_change_dict:
            drcs_id = sql.find_one(f"select drcs_id from drcs_doc  where id = {drcs_doc_id}")
            if drcs_id:
                sql.update_one_by_dict("drcs", drcs_change_dict, drcs_id[0])


def delete_drcs(drcs_id):
    """删除DRCS"""
    sql = SQL()
    sql.execute_cmd(f"delete from drcs where id = {drcs_id}")
    sql.execute_cmd(f"delete from doc_review where drcs_id = {drcs_id}")


def get_drcs_info_from_contract_id(contract_id: int):
    """通过合同id从合同中查询关于DRCS的信息"""
    contract_info: dict = {}
    df_contract = Public_Data().Df_Contract
    contract_info_df = df_contract.loc[df_contract["id"] == contract_id]
    con_info: DataFrame = contract_info_df[["project", "checker", "approver", "channel_code", 'file_copy']]
    con_inf_dic = con_info.to_dict("list")
    contract_info["project"] = con_inf_dic["project"][0]
    contract_info["checker"] = con_inf_dic["checker"][0]
    contract_info["approver"] = con_inf_dic["approver"][0]
    contract_info["channel_code"] = con_inf_dic["channel_code"][0]
    contract_info["file_copy"] = con_inf_dic["file_copy"][0]
    return contract_info


def delete_idrs(id_list):
    delete_by_id_list("idrs", id_list)


def update_url(table_name, data_id, url_str):
    if id:
        sql_str = f'UPDATE  {table_name} SET url={url_str} WHERE id = {data_id}'
        sql = SQL()
        sql.execute_cmd(sql_str)


def update_status(table_name, data_id, status):
    if id:
        if int(status):
            sql_str = f'UPDATE  {table_name} SET status={int(status)} WHERE id = {data_id}'
            sql = SQL()
            sql.execute_cmd(sql_str)


def update_url_status(table_name, data_id, url_str, status):
    if id:
        sql_str = f'UPDATE  {table_name} SET url={url_str}, status= {status} WHERE id = {data_id}'
        sql = SQL()
        sql.execute_cmd(sql_str)


def insert_file_path(file_path, file_type, file_once_id):
    sql = SQL()
    col_list = ["file_path", "file_type", "file_once_id"]
    value = [file_path, file_type, file_once_id]
    sql.insert_one("file_path", col_list, value)

# endregion
